package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Author Yang
 * @Date 2023/3/2 11:44
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private HttpSession session;

    //查询所有
    @Override
    public List<Category> findAll() {
        List<Category> list = categoryMapper.findAll();
        return list;
    }

    //新增
    @Override
    public void save(Category category) {
        //分类id
        long id = IdUtil.createSnowflake(1, 1).nextId();
        category.setId(id);
//        //创建时间-修改时间
//        category.setUpdateTime(new Date());
//        category.setCreateTime(new Date());
//        //创建人-修改人
//        Employee attribute = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        category.setUpdateUser(attribute.getId());
//        category.setCreateUser(attribute.getId());

        categoryMapper.save(category);
    }

    //修改
    @Override
    public void update(Category category) {
//        //修改时间
//        category.setUpdateTime(new Date());
//        //修改人
//        Employee attribute = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        category.setUpdateUser(attribute.getId());

        categoryMapper.updateById(category);
    }

    //删除
    @Override
    public void deleteById(Long id) {
        //菜品
        Integer dish = categoryMapper.countDish(id);
        if (dish > 0) {
//            return ResultInfo.error("该分类下有菜品，不允许删除");
            throw new CustomException("该分类下有菜品，不允许删除");
        }

        Integer SetMeal = categoryMapper.countSetMeal(id);
        if(SetMeal > 0){
//            return ResultInfo.error("该套餐下有菜品，不允许删除");
            throw new CustomException("该套餐下有菜品，不允许删除");
        }

        categoryMapper.deleteById(id);

    }

    //查询分类列表
    @Override
    public List<Category> list(Integer type) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType,type);
        List<Category> list = categoryMapper.selectList(qw);
        return list;
    }
}
























